﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Script.Serialization;
using System.Configuration;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using com.evaair.mall;

public partial class OrderSummaryAndAmount : System.Web.UI.Page
{
  protected OrderInfo oi;
  List<FreePlusList> liFreePlus;
  List<BuyPlusItem> liBuyPlus;
  List<EcouponItem> liEcoupon;

  protected void Page_Load(object sender, EventArgs e)
  {
    //購物車為null導回首頁
    if (Session["ShoppingCart"] == null )
    {
      Response.Redirect("~/Home.aspx");
    }
    //建立訂單、加贈、加購物件
    CheckObject();
    //確認登入資訊
    CheckMember();
    if (!Page.IsPostBack)
    {
      //取得訂單資訊
      GetOrderInfo();
      //取得(1)購物清單(2)加贈購清單資料列表(3)取得E-coup​on
      BindShoppingList();
      //計算費用
      CalcPrice();
    }
  }

  /// <summary>
  /// 建立物件(訂單、加贈、加購、Ecoupon)
  /// </summary>
  private void CheckObject()
  {

    // 建立訂單物件
    if (Session["OrderInfo"] == null)
    {
      oi = new OrderInfo();
      oi.MemberID = "";
      oi.IsLogin = "";
      oi.Password = "";
      oi.MemberType = "3";
      oi.DiscType = "3";
      oi.PayType = "1";
      oi.ChooseECouponNo = "";
      oi.BuyerID = "";
      oi.MileMemberID = "";
      Session["OrderInfo"] = oi;
    }
    else
    {
      oi = (OrderInfo)Session["OrderInfo"];
    }

    // 建立加贈物件
    if (Session["FreePlusList"] == null)
    {
      liFreePlus = new List<FreePlusList>();
      Session["FreePlusList"] = liFreePlus;
    }
    else
    {
      liFreePlus = (List<FreePlusList>)Session["FreePlusList"];
    }

    // 建立加購物件
    if (Session["BuyPlusItem"] == null)
    {
      liBuyPlus = new List<BuyPlusItem>();
      Session["BuyPlusItem"] = liBuyPlus;
    }
    else
    {
      liBuyPlus = (List<BuyPlusItem>)Session["BuyPlusItem"];
    }

    // 建立Ecoupon物件
    liEcoupon = new List<EcouponItem>();

  }

  /// <summary>
  /// 確認登入資訊
  /// </summary>
  private void CheckMember()
  {
    //判斷是否已會員登入
    if (!string.IsNullOrEmpty(HttpContext.Current.User.Identity.Name))
    {
      //已登入(個人會員或企業會員)
      oi.MemberID = HttpContext.Current.User.Identity.Name;
      if (HttpContext.Current.Request.Cookies["LoginInfo"] != null)
      {
        HttpCookie hc = HttpContext.Current.Request.Cookies["LoginInfo"] as HttpCookie;
        //是否重選付款方式
        bool isNewLogin =true ;
        if (oi.MemberType != null && oi.MemberType == hc.Values["AuthType"].ToString())
        {
          isNewLogin = false;
        }
        oi.MemberType = hc.Values["AuthType"].ToString();
        oi.IsLogin = "1";
        oi.Password = hc.Values["Password"].ToString();
        //個人會員將資料帶入
        if (oi.MemberType == "1" & isNewLogin)
        {
          //只要有哩上加禮的商品，則一開始要給里程抵扣的會員ID預設值 2013/12/20 by Adams
          oi.MileMemberID = string.IsNullOrEmpty(oi.MileMemberID) ? oi.MemberID : oi.MileMemberID;
             
          B2C_MALL_ACCOUNT ws = new B2C_MALL_ACCOUNT();
          ws.Url = ConfigurationManager.AppSettings["B2C_MALL_ACCOUNT"].ToString();
          string strJson = ws.B2C_MALL_GetMemberData(CommonUtil.GetWebDevice(), oi.MemberID);
          JObject jObj = JsonConvert.DeserializeObject<JObject>(strJson);
          if (jObj["Is_Valid"].ToString() == "Y")
          {
            oi.BuyerName = jObj["F_CHT_NAME"].ToString();
            oi.BuyerPhone = jObj["F_TEL_HOME"].ToString();
            oi.BuyerTel = jObj["F_TEL_OFFICE"].ToString();
            oi.BuyerMobile = jObj["F_MOBILE"].ToString();
            oi.BuyerZIP = jObj["F_ZIP"].ToString();
            oi.BuyerCity = jObj["CITY"].ToString();
            oi.BuyerArea = jObj["TOWNS"].ToString();
            oi.BuyerAddress = jObj["F_ADDR1"].ToString();
            oi.BuyerEamil = jObj["F_EMAIL"].ToString();
            oi.BuyerFax = jObj["F_FAX"].ToString();
          }
        }
        //非會員輸入身份證登入查詢ECOUPON後，會有登入資訊，再購買商品結帳時結帳金額沒有出現，所以將Login及Password設為空值
        //by Andy 2013/12/23
        if (oi.MemberType == "3") 
        {
            oi.IsLogin = "";
            oi.Password = "";
        }
      }
    }
    else
    {
      //非會員
      oi.MemberType = "3";
      oi.IsLogin = "";
      oi.Password = "";
      //身分證
      if (HttpContext.Current.Request.Cookies["TWIdentity"] != null)
      {
        HttpCookie hc = HttpContext.Current.Request.Cookies["TWIdentity"] as HttpCookie;
        oi.MemberID = hc.Value.ToUpper();
        oi.BuyerID = hc.Value.ToUpper();
      }
      else
      {
        oi.MemberID = "";
        oi.BuyerID = "";
      }
    }
    //紀錄OrderInfo
    Session["OrderInfo"] = oi;
  }
  
  /// <summary>
  /// 取得訂單資訊
  /// </summary>
  private void GetOrderInfo()
  {
    if (oi.PayType == "1")
    {
      rbPayType1.Checked = true;
    }
    else if (oi.PayType == "2")
    {
      rbPayType2.Checked = true;
    }
    else
    {
      rbPayType3.Checked = true;
    }
    if (oi.DiscType == "1")
    {
      rbDiscType1.Checked = true;
      hfECoupon.Value = oi.ChooseECouponNo;

    }
    else if (oi.DiscType == "2")
    {
      rbDiscType2.Checked = true;
    }
    else
    {
      rbDiscType3.Checked = true;
    }

  }

  /// <summary>
  /// (1)購物清單 
  /// (2)加贈購清單資料列表(含驗證)
  /// (3)E-coup​on(含驗證)
  /// </summary>
  private void BindShoppingList()
  {
    ShoppingCart userShoppingCart = (ShoppingCart)Session["ShoppingCart"];
    if (userShoppingCart != null & userShoppingCart.CartItems.Count > 0)
    {
      //取得E-coup​on
      B2C_MALL_ORDER ws = new B2C_MALL_ORDER();
      ws.Url = ConfigurationManager.AppSettings["B2C_MALL_ORDER"].ToString();
      string strOrderList = CommonUtil.ShoppingCartToOrderListSerialize(userShoppingCart);
      string strJsonE = ws.B2C_MALL_ValidateOrderInfo(CommonUtil.GetWebDevice(), oi.MemberID, oi.MemberType, "1", oi.PayType
        , strOrderList, "", "", "", "", oi.IsLogin, oi.Password, "2", oi.ChooseECouponNo, "", "", oi.MileMemberID);
      JObject jObjE = JsonConvert.DeserializeObject<JObject>(strJsonE);
      if (jObjE["Is_Valid"].ToString() == "Y")
      {
        //E-coup​on (立即扣抵E-coup​on:5，帳號E-coup​on:3)
        if (!string.IsNullOrEmpty(jObjE["pEcoupon_Ary_List"].ToString()))
        {
          foreach (var ja in (JArray)jObjE["pEcoupon_Ary_List"])
          {
            EcouponItem ei = new EcouponItem();
            ei.DiscountNo = ja["ECOUPON_NO"].ToString();
            ei.Price = ja["ECOUPON_PRICE"].ToString();
            //除了Type=5之外，全部秀Range
            if (ja["ECOUPON_TYPE"].ToString() != "5")
            {
              ei.Range = ja["RangeFrom"].ToString() + "~" + ja["RangeTo"].ToString();
            }
            else 
            {
              ei.Range = "限本次消費使用";
            }
            ei.Memo = "";
            liEcoupon.Add(ei);
          }
        }

        if (liEcoupon.Count > 0)
        {
          divECouponMsg1.Visible = false;
          gvECoupon.DataSource = liEcoupon;
          gvECoupon.DataBind();
          lblNoECoupon.Visible = false;
          //不論任何登入身分，當從購物車(購物袋)點擊”結帳”進入結帳流程第一個頁面時
          //只要有任何 E-Coupon 可選 (不須判定是否有限定本次消費的 E-Coupon)
          if (!Page.IsPostBack)
          {
            Page.ClientScript.RegisterStartupScript(this.GetType(), 
              "E-Coupon",
              "$('#spanMsg').html('溫馨小提醒：您本次消費有 E-Coupon 可以選擇!');lightbox($('.divMessageLightbox').prop('outerHTML'));", 
              true);　
          }
        }
        else
        {
          //顯示沒有E-Coupon訊息
          rbDiscType1.Enabled = false;
          lblNoECoupon.Visible = true;
        }

        //E-Coupon驗證(刪除修改等驗證已選取的Ecoupon是否存在)
        if (oi.DiscType == "1")
        {
          bool isCheck = false;
          if (!string.IsNullOrEmpty(hfECoupon.Value))
          {

            foreach (EcouponItem ei in liEcoupon)
            {
              if (ei.DiscountNo == hfECoupon.Value)
              {
                isCheck = true;
                break;
              }
            }
          }
          if (!isCheck)
          {
            if (!string.IsNullOrEmpty(oi.ChooseECouponNo))
            {
              Page.ClientScript.RegisterStartupScript(this.GetType(),
               "E-Coupon",
               "$('#spanMsg').html('溫馨提醒：您的必須重新選擇E-Coupon !');lightbox($('.divMessageLightbox').prop('outerHTML'));",
               true);　
            }
            oi.DiscType = "3";
            oi.ChooseECouponNo = "";
            rbDiscType3.Checked = true;
            //紀錄OrderInfo
            Session["OrderInfo"] = oi;
          }
        }
      }

      //購物車、加贈購清單資料列表
      string strJson = ws.B2C_MALL_ValidateOrderInfo(CommonUtil.GetWebDevice(), oi.MemberID, oi.MemberType, oi.DiscType, oi.PayType
        , strOrderList, "", "", "", "", oi.IsLogin, oi.Password, "2", oi.ChooseECouponNo, "", "", oi.MileMemberID);
      JObject jObj = JsonConvert.DeserializeObject<JObject>(strJson);
      //購物車確認
      if (jObj["pItemList_Ary_List"]!=null)
      {
        dynamic dynItemList = (dynamic)jObj["pItemList_Ary_List"];
        foreach (CartItem ci in userShoppingCart.CartItems)
        {
          foreach (var ja in dynItemList)
          {
            if (ja["Smas_Code"].ToString() == ci.SMAS_CODE)
            {
              userShoppingCart.UpdateItemStatusMemo(ci.SMAS_CODE
                  , ja["Prod_Status"].ToString(), ja["Prod_Memo"].ToString());
              break;
            }
          }
        }
      }


      gvShoppingList.DataSource = userShoppingCart.CartItems;
      gvShoppingList.DataBind();
      if (jObj["Is_Valid"].ToString() == "Y")
      {
        //隨機加贈
        if (!string.IsNullOrEmpty(jObj["pFreePlusRandom_List"].ToString())
            & jObj["pFreePlusRandom_List"].ToString() != "[]")
        {
          gvFreePlusRandom.DataSource = jObj["pFreePlusRandom_List"];
          gvFreePlusRandom.DataBind();
        }
        else
        {
          gvFreePlusRandom.DataSource = null;
          gvFreePlusRandom.DataBind();
        }

        //選擇加贈
        if (!string.IsNullOrEmpty(jObj["pFreePlus_Ary_List"].ToString()))
        {
          dynamic dynFreePlusAryList = (dynamic)jObj["pFreePlus_Ary_List"];
          //要取下一層判斷[{"pFreePlus_List":null}]
          if (!string.IsNullOrEmpty(dynFreePlusAryList[0].pFreePlus_List.ToString()))
          {
            gvFreePlus.DataSource = dynFreePlusAryList[0].pFreePlus_List;
            gvFreePlus.DataBind();

            //預設為第一筆選取與紀錄選擇加贈
            foreach (GridViewRow gr in gvFreePlus.Rows)
            {
              //預設為第一筆選取
              ((RadioButton)gr.FindControl("rbFreePlusSelect")).Checked = true;
              break;
            }
          }
        }
        else
        {
          gvFreePlus.DataSource = null;
          gvFreePlus.DataBind();
        }

        //紀錄加贈
        SaveFreePlus();

        //加購
        if (!string.IsNullOrEmpty(jObj["pBuyPlus_Ary_List"].ToString()))
        {
          gvBuyPlus.DataSource = jObj["pBuyPlus_Ary_List"];
        }
        else
        {
          //清空加購列表與清除加購選取
          gvBuyPlus.DataSource = null;
          liBuyPlus.Clear();
          Session["BuyPlusItem"] = liBuyPlus;
        }
        gvBuyPlus.DataBind();

      }

      //加購顯示勾取與驗證
      if (liBuyPlus.Count > 0)
      {
        List<BuyPlusItem> liCheck = new List<BuyPlusItem>();
        foreach (BuyPlusItem bpi in liBuyPlus)
        {
          foreach (GridViewRow gr in gvBuyPlus.Rows)
          {
            if (bpi.SMAS_CODE == ((Literal)gr.FindControl("ltlSMAS_CODE")).Text)
            {
              ((CheckBox)gr.FindControl("cbBuyPlusSelect")).Checked = true;
              liCheck.Add(bpi);
            }
          }
        }
        //紀錄
        Session["BuyPlusItem"] = liCheck;
      }

      //顯示抵扣哩程判斷與取得哩程數總計
      bool isMileAge = false;
      //哩程數總計
      int intMileage = 0;
      foreach (CartItem ci in userShoppingCart.CartItems)
      {
        if (!string.IsNullOrEmpty(ci.Mileage))
        {
          isMileAge = true;
          intMileage += Convert.ToInt32(ci.Mileage);
        }
      }
      if (isMileAge)
      {
        BindMileage(intMileage);
      }
    }
    else 
    {
      //oi.ChooseECouponNo = "";
      //oi.MileMemberID = "";
      //Session["OrderInfo"] = "";
      Session["OrderInfo"] = null;
      liFreePlus.Clear();
      Session["FreePlusList"] = liFreePlus;
      liBuyPlus.Clear();
      Session["BuyPlusItem"] = liBuyPlus;
      liEcoupon.Clear();

      //無購物車資料
      gvShoppingList.DataSource = null;
      gvShoppingList.DataBind();
      //清空隨機加贈
      gvFreePlusRandom.DataSource = null;
      gvFreePlusRandom.DataBind();
      //清空選擇加贈
      gvFreePlus.DataSource = null;
      gvFreePlus.DataBind();
      //清空加購
      gvBuyPlus.DataSource = null;
      gvBuyPlus.DataBind();
      //清空自有哩程
      gvMileageP.DataSource = null;
      gvMileageP.DataBind();
      //清空受贈哩程
      gvMileageO.DataSource = null;
      gvMileageO.DataBind();

    
    }


  }

  /// <summary>
  /// 計算費用
  /// </summary>
  private void CalcPrice()
  {
    bool isOK = false;
    ShoppingCart userShoppingCart = (ShoppingCart)Session["ShoppingCart"];
    if (userShoppingCart!=null & userShoppingCart.CartItems.Count > 0)
    {
      B2C_MALL_ORDER ws = new B2C_MALL_ORDER();
      ws.Url = ConfigurationManager.AppSettings["B2C_MALL_ORDER"].ToString();
      //購物車資料
      string strOrderList = CommonUtil.ShoppingCartToOrderListSerialize(userShoppingCart);
      //加購資料(無資料傳空字串"")
      string strBuyPlus = liBuyPlus.Count > 0 ? JsonConvert.SerializeObject(liBuyPlus) : "";

      string strJson = ws.B2C_MALL_ValidateOrderInfo(CommonUtil.GetWebDevice(), oi.MemberID, oi.MemberType, oi.DiscType, oi.PayType
          , strOrderList.ToString(), "", "", "", "", oi.IsLogin, oi.Password, "2", oi.ChooseECouponNo, strBuyPlus, "", oi.MileMemberID);

      JObject jObj = JsonConvert.DeserializeObject<JObject>(strJson);

      if (jObj["Is_Valid"].ToString() == "Y" & jObj["pOrderSumList_Ary"] != null)
      {
        isOK = true;
        lbtn_ConfirmOrder.Visible = true;
        var ja = jObj["pOrderSumList_Ary"];
        //單價總計(含稅) 
        ltlPriceSum.Text = string.Format("{0:$ #,##0元}", Convert.ToInt32(ja["TotalPriceSum"].ToString()));
        //折扣金額(含稅)=discountSum - eCouponSum
        ltlDiscountSum.Text = string.Format("{0:$ #,##0元}", Convert.ToInt32(ja["discountSum"].ToString()));
        //E-coupon金額
        if (ja["eCouponSum"].ToString() != "null" & !string.IsNullOrEmpty(ja["eCouponSum"].ToString()))
        {
          ltlECouponSum.Text = string.Format("{0:$ #,##0元}", Convert.ToInt32(ja["eCouponSum"].ToString()));
        }
        else
        {
          ltlECouponSum.Text = "$ 0元";
        }
        //運費
        ltlTransFee.Text = string.Format("{0:$ #,##0元}", Convert.ToInt32(ja["TransFee"].ToString()));
        //扣抵總哩程數
        ltlMileSum.Text = string.Format("{0:#,##0哩}", Convert.ToInt32(ja["mile_Sum"].ToString()));
        //消費總計(含稅)
        decimal decTotal=Convert.ToDecimal(ja["nTheMoneyWeGet"].ToString());
        if (decTotal<0)
        {
            //金額小於0處理
            decTotal = 0;
            lbtn_ConfirmOrder.Visible = false;
        }
        ltlnTheMoneyWeGet.Text = string.Format("{0:$ #,##0元}", decTotal);
        ltlMileSum2.Text = ltlMileSum.Text;

      }
    }

    if (!isOK)
    {
      //無資料或資料異常不可下一步
      lbtn_ConfirmOrder.Visible = false;
      //單價總計(含稅) 
      ltlPriceSum.Text = "$ -元";
      //折扣金額(含稅)=discountSum - eCouponSum
      ltlDiscountSum.Text = "$ -元";
      //E-coupon金額
      ltlECouponSum.Text = "$ -元";
      //運費
      ltlTransFee.Text = "$ -元";
      //扣抵總哩程數
      ltlMileSum.Text = "-哩";
      //消費總計(含稅)
      ltlnTheMoneyWeGet.Text = "$ -元";
      ltlMileSum2.Text = ltlMileSum.Text;
    }
    //Literal1.Text = oi.PayType.Replace("1", "信用卡").Replace("2", "銀行匯款").Replace("3", "國泰世華銀行ATM");
    //Literal1.Text += ";" + oi.DiscType.Replace("1", "e-Coupon").Replace("2", "聯名卡").Replace("3", "都未使用") + "";
    //Literal1.Text += " - ECouponNO:" + oi.ChooseECouponNo;
    //Literal1.Text += " - 加贈:" + liFreePlus.Count.ToString();
    //Literal1.Text += " - 加購:" + liBuyPlus.Count.ToString();
    //Literal1.Text += " - 哩程:" + oi.MileMemberID.ToString();
  }

  /// <summary>
  /// 取得哩程(自有與受贈)
  /// </summary>
  private void BindMileage(int intMileage)
  {

    B2C_MALL_ORDER ws = new B2C_MALL_ORDER();
    ws.Url = ConfigurationManager.AppSettings["B2C_MALL_ORDER"].ToString();
    string jsonString = ws.B2C_MALL_GetmbrMileList(CommonUtil.GetWebDevice(), oi.MemberID);
    JObject jObject = JsonConvert.DeserializeObject<JObject>(jsonString);

    if (jObject["Is_Valid"].ToString() == "Y")
    {
      //自有哩程      
      dynamic MileageP = ((JArray)jObject["pMileage_Ary_List"])
        .Where(m => m["ID"].ToString() == "P");
      gvMileageP.DataSource = MileageP;
      gvMileageP.DataBind();

      //受贈哩程
      dynamic MileageS = ((JArray)jObject["pMileage_Ary_List"])
        .Where(m => m["ID"].ToString() != "P");
      gvMileageO.DataSource = MileageS;
      gvMileageO.DataBind();

      //哩程驗證與選取
      bool isCheck=false;
      foreach (GridViewRow gr in gvMileageP.Rows)
      {
        RadioButton rbMileageSelect = (RadioButton)gr.FindControl("rbMileageSelect");
        Literal ltlMileage = (Literal)gr.FindControl("ltlMileage");
        if (Convert.ToInt64(ltlMileage.Text.Replace(",","")) < intMileage)
        {
          rbMileageSelect.Enabled = false;
        }
        else if (rbMileageSelect.ToolTip == oi.MileMemberID)
        {
          rbMileageSelect.Checked = true;
          isCheck = true;
        }
      }
      foreach (GridViewRow gr in gvMileageO.Rows)
      {
        RadioButton rbMileageSelect = (RadioButton)gr.FindControl("rbMileageSelect");
        Literal ltlMileage = (Literal)gr.FindControl("ltlMileage");
        if (Convert.ToInt64(ltlMileage.Text.Replace(",", "")) < intMileage)
        {
          rbMileageSelect.Enabled = false;
        }
        else if (rbMileageSelect.ToolTip == oi.MileMemberID)
        {
          rbMileageSelect.Checked = true;
          isCheck = true;
        }
      }
      if (!isCheck)
      {
        oi.MileMemberID = "";
      }

    }
  }

  /// <summary>
  /// 數量修改與商品刪除
  /// </summary>
  protected void gvShoppingList_RowCommand(object sender, GridViewCommandEventArgs e)
  {
    ShoppingCart userShoppingCart = (ShoppingCart)Session["ShoppingCart"];
    if (userShoppingCart != null)
    {
      if (e.CommandName == "RowUpdate")
      {
        GridViewRow gvr = ((LinkButton)e.CommandSource).Parent.Parent as GridViewRow;
        TextBox txtboxQty = (TextBox)gvr.FindControl("txtboxQty");
        if (!string.IsNullOrEmpty(txtboxQty.Text) && Convert.ToInt32(txtboxQty.Text) > 0)
        {
          userShoppingCart.UpdateItem(e.CommandArgument.ToString(), int.Parse(txtboxQty.Text));
        }
        else
        {
          userShoppingCart.UpdateItem(e.CommandArgument.ToString(), 1);
          txtboxQty.Text = "1";
        }
      }
      else if (e.CommandName == "RowDel")
      {
        userShoppingCart.RemoveItem(e.CommandArgument.ToString());
        //更新Master Page中的筆數
        Label myCartCounter = Master.Master.FindControl("myCartCounter") as Label;
        myCartCounter.Text = userShoppingCart.GetItemCount().ToString();
        if (userShoppingCart.GetItemCount() > 0)
        {
          lbtn_ConfirmOrder.Visible = true;
        }
        else
        {
          lbtn_ConfirmOrder.Visible = false;
        }
      }
    }

    //取得(1)購物清單(2)加贈購清單資料列表(3)取得E-coup​on
    BindShoppingList();
    //計算費用
    CalcPrice();

  }

  /// <summary>
  /// 加贈選取(選擇加贈)
  /// </summary>
  protected void rbFreePlusSelect_CheckedChanged(object sender, EventArgs e)
  {
    SaveFreePlus();
  }

  /// <summary>
  /// 紀錄加贈
  /// </summary>
  private void SaveFreePlus()
  {
    //清除所有加贈資料紀錄
    liFreePlus.Clear();

    //隨機加贈確認
    foreach (GridViewRow gr in gvFreePlusRandom.Rows)
    {
      FreePlusList fpi = new FreePlusList();
      fpi.B2C_CODE = ((Literal)gr.FindControl("ltlB2C_CODE")).Text;
      fpi.SMAS_CODE = ((Literal)gr.FindControl("ltlSMAS_CODE")).Text;
      fpi.Promotion_ID = ((Literal)gr.FindControl("ltlPromotion_ID")).Text;
      fpi.Prd_Type = ((Literal)gr.FindControl("ltlPrd_Type")).Text;
      fpi.ProductName = ((Literal)gr.FindControl("ltlB2C_CODE_NAME")).Text;
      fpi.ImagePath = ((System.Web.UI.HtmlControls.HtmlImage)gr.FindControl("imgPath")).Src;
      //fpi.ImagePath = ((Image)gr.FindControl("imgPath")).ImageUrl;
      liFreePlus.Add(fpi);
    }
    //選擇加贈確認
    foreach (GridViewRow gr in gvFreePlus.Rows)
    {
      if (((RadioButton)gr.FindControl("rbFreePlusSelect")).Checked == true)
      {
        FreePlusList fpi = new FreePlusList();
        fpi.B2C_CODE = ((Literal)gr.FindControl("ltlB2C_CODE")).Text;
        fpi.SMAS_CODE = ((Literal)gr.FindControl("ltlSMAS_CODE")).Text;
        fpi.Promotion_ID = ((Literal)gr.FindControl("ltlPromotion_ID")).Text;
        fpi.Prd_Type = ((Literal)gr.FindControl("ltlPrd_Type")).Text;
        fpi.ProductName = ((Literal)gr.FindControl("ltlB2C_CODE_NAME")).Text;
        fpi.ImagePath = ((System.Web.UI.HtmlControls.HtmlImage)gr.FindControl("imgPath")).Src;
        liFreePlus.Add(fpi);
        break;
      }
    }
    //紀錄加贈
    Session["FreePlusList"] = liFreePlus;
  }

  /// <summary>
  /// 加購選取
  /// </summary>
  protected void cbBuyPlusSelect_CheckedChanged(object sender, EventArgs e)
  {
    //清除
    liBuyPlus.Clear();
    //將所有選取加入
    foreach (GridViewRow gr in gvBuyPlus.Rows)
    {
      CheckBox cbBuyPlusSelect = (CheckBox)gr.FindControl("cbBuyPlusSelect");
      if (cbBuyPlusSelect.Checked)
      {
        BuyPlusItem bpi = new BuyPlusItem();
        bpi.B2C_CODE = ((Literal)gr.FindControl("ltlB2C_CODE")).Text;
        bpi.SMAS_CODE = ((Literal)gr.FindControl("ltlSMAS_CODE")).Text;
        bpi.Promotion_ID = ((Literal)gr.FindControl("ltlPromotion_ID")).Text;
        bpi.Prd_Type = ((Literal)gr.FindControl("ltlPrd_Type")).Text;
        bpi.price = ((Literal)gr.FindControl("ltlprice")).Text;
        liBuyPlus.Add(bpi);
      }
    }
    //紀錄加購
    Session["BuyPlusItem"] = liBuyPlus;
    //取得(1)購物清單(2)加贈購清單資料列表(3)取得E-coup​on
    BindShoppingList();
    //計算費用
    CalcPrice();
  }

  /// <summary>
  /// 哩程選取
  /// </summary>
  protected void rbMileageSelect_CheckedChanged(object sender, EventArgs e)
  {
    oi.MileMemberID = ((RadioButton)sender).ToolTip;
    //紀錄OrderInfo
    Session["OrderInfo"] = oi;
    //取得(1)購物清單(2)加贈購清單資料列表(3)取得E-coup​on
    BindShoppingList();
    //計算費用
    CalcPrice();
  }

  /// <summary>
  /// 付款方式與折扣變更
  /// </summary>
  protected void rbPayTypeDiscType_CheckedChanged(object sender, EventArgs e)
  {
    //紀錄OrderInfo(付款方式與折扣)
    SaveOrderInfo();
    //取得(1)購物清單(2)加贈購清單資料列表(3)取得E-coup​on
    BindShoppingList();
    //計算費用
    CalcPrice();
  }

  /// <summary>
  /// ECoupon選取
  /// </summary>
  protected void lbtnECoupon_Click(object sender, EventArgs e)
  {
    if (hfECoupon.Value.Length > 0)
    {
      rbDiscType1.Checked = true;
      //紀錄OrderInfo(付款方式與折扣)
      SaveOrderInfo();
      //重新計算金額
      CalcPrice();
    }
  }

  /// <summary>
  /// ECoupon取消
  /// </summary>javascript:__doPostBack('ctl00$ctl00$Content$NestedContent$lbtn_ConfirmOrder','')
  protected void lbtnECouponCancel_Click(object sender, EventArgs e)
  {
    //紀錄OrderInfo
    SaveOrderInfo();
    //重新計算金額
    CalcPrice();
  }

  /// <summary>
  /// 確定結帳
  /// </summary>
  protected void lbtn_ConfirmOrder_Click(object sender, EventArgs e)
  {
    //紀錄OrderInfo(付款方式與折扣)
    SaveOrderInfo();
    Response.Redirect("OrderDetailAndPayment.aspx");
  }

  /// <summary>
  /// 紀錄OrderInfo(付款方式與折扣)
  /// </summary>
  private void SaveOrderInfo()
  {
    //付款方式
    if (rbPayType1.Checked)
    {
      //信用卡
      oi.PayType = "1";
    }
    else if (rbPayType2.Checked)
    {
      //銀行匯款 
      oi.PayType = "2";
    }
    else
    {
      //國泰世華銀行ATM  
      oi.PayType = "3";
    }

    //折扣
    if (rbDiscType1.Checked)
    {
      //ECouponNo
      if (!string.IsNullOrEmpty(hfECoupon.Value))
      {
        oi.DiscType = "1";
        oi.ChooseECouponNo = hfECoupon.Value;
      }
      else
      {
        rbDiscType3.Checked = true;
        oi.DiscType = "3";
        oi.ChooseECouponNo = "";
      }
    }
    if (rbDiscType2.Checked)
    {
      //長榮航空聯名卡95折優惠
      oi.DiscType = "2";
      oi.ChooseECouponNo = "";
    }
    else if (rbDiscType3.Checked)
    {
      oi.DiscType = "3";
      oi.ChooseECouponNo = "";
    }
    //紀錄OrderInfo
    Session["OrderInfo"] = oi;
  }

  /// <summary>
  /// 自有哩程click事件設定
  /// </summary>
  protected void gvMileageP_RowDataBound(object sender, GridViewRowEventArgs e)
  {
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
      ((RadioButton)e.Row.FindControl("rbMileageSelect")).Attributes.Add("onclick", "RadioMileage(this)");
    }
  }

  /// <summary>
  /// 受贈哩程click事件設定
  /// </summary>
  protected void gvMileageO_RowDataBound(object sender, GridViewRowEventArgs e)
  {
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
      ((RadioButton)e.Row.FindControl("rbMileageSelect")).Attributes.Add("onclick", "RadioMileage(this)");
    }
  }

  /// <summary>
  /// ECoupon Click設定
  /// </summary>
  protected void gvECoupon_RowDataBound(object sender, GridViewRowEventArgs e)
  {
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
      RadioButton rbSelect = (RadioButton)e.Row.FindControl("rbECouponSelect");
      rbSelect.Attributes.Add("onclick", "RadioECoupon(this,'" + rbSelect.ToolTip + "')");
    }
  }

  /// <summary>
  /// 加贈Click 事件設定
  /// </summary>
  protected void gvFreePlus_RowDataBound(object sender, GridViewRowEventArgs e)
  {
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
      RadioButton rbSelect = (RadioButton)e.Row.FindControl("rbFreePlusSelect");
      rbSelect.Attributes.Add("onclick", "RadioFreePlus(this,'" + rbSelect.ToolTip + "')");
    }
  }


}